package com.sunny.ynhz.ui;

import android.app.Activity;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.jauker.widget.BadgeView;
import com.sunny.ynhz.R;
import com.sunny.ynhz.api.HttpManager;
import com.sunny.ynhz.api.NetUrl;
import com.sunny.ynhz.api.subscriber.ApiSubscriber;
import com.sunny.ynhz.app.SNNApplication;
import com.sunny.ynhz.bean.LoginBean;
import com.sunny.ynhz.model.ProblemTypeModel;
import com.sunny.ynhz.model.RiverChiefModel;
import com.sunny.ynhz.model.RiverMsgModel;
import com.sunny.ynhz.service.PlayerMusicService;
import com.sunny.ynhz.service.WarnService;
import com.sunny.ynhz.ui.base.BaseActivity;
import com.sunny.ynhz.call.ICutDownTime;
import com.sunny.ynhz.event.ClickEvent;
import com.sunny.ynhz.ui.index.NewPatrolFragment;
import com.sunny.ynhz.ui.index.DailyFragment;
import com.sunny.ynhz.ui.index.MineFragment;
import com.sunny.ynhz.ui.index.NewPatrolFragment1;
import com.sunny.ynhz.ui.index.StatisticsFragment;
import com.sunny.ynhz.ui.index.UserFragment;
import com.sunny.ynhz.ui.login.LoginActivity;
import com.sunny.ynhz.utils.AlertUtils;
import com.sunny.ynhz.utils.AppManager;
import com.sunny.ynhz.utils.CheckVersionUtlils;
import com.sunny.ynhz.utils.DeviceMsgUtils;
import com.sunny.ynhz.utils.JobSchedulerManager;
import com.sunny.ynhz.utils.SPUtil;
import com.sunny.ynhz.utils.ScreenBroadcastListener;
import com.sunny.ynhz.utils.ScreenManager;
import com.sunny.ynhz.utils.SpashTimeUtils;
import com.sunny.ynhz.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import io.rong.callkit.RongCallKit;
import io.rong.imkit.RongIM;
import io.rong.imkit.manager.IUnReadMessageObserver;
import io.rong.imkit.model.UIConversation;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener, ICutDownTime {
    private Fragment nowFragment1;
    @BindView(R.id.index_rg)
    RadioGroup index_rg;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.rl_spash)
    View rl_spash;
    @BindView(R.id.rb_statics)
    RadioButton rb_statics;
    @BindView(R.id.rb_patrol)
    RadioButton rb_patrol;
    @BindView(R.id.rb_daily)
    RadioButton rb_daily;
    @BindView(R.id.rb_user)
    RadioButton rb_user;
    @BindView(R.id.rb_bag)
    View rb_bag;
    private MineFragment instanceMineFragment;
    public NewPatrolFragment newPatrolFragment;
    private StatisticsFragment instanceStatisticsFragment;
    private DailyFragment instanceDailyFragment;
    private SpashTimeUtils spashTimeUtils;
    private Activity activity;
    private RequestQueue mQueue;
    private BadgeView badgeView;
    private boolean isSwitchUserFrahment = false;
    int type;
    private Intent intentService;
    private AlertUtils alertUtils;
    private Intent intent;
    private ScreenManager screenManager;
    private IUnReadMessageObserver unReadMessageObserver;
    private UserFragment userFragment;
    private boolean isFocus = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setBackgroundDrawable(null);
        setContentView(R.layout.activity_main);
        initJspush();
        if (!isTaskRoot()) {
            finish();
            return;
        }
        activity = this;
        type = getIntent().getIntExtra("type", -5);
        if (type == -5) {
            if (!SPUtil.get("login_name", "null").toString().equals("null") && (!SPUtil.get("password", "null").toString().equals("null")) && (!TextUtils.isEmpty(SPUtil.get("username", "").toString()))) {
                String login_name = SPUtil.get("login_name", "").toString();
                String password = SPUtil.get("password", "").toString();
                String devicecode = DeviceMsgUtils.getIMEI(activity);
                login(login_name, password, true, devicecode);
            } else {
                doActivity(LoginActivity.class);
                finish();
                return;
            }
        }
        if (!(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)) {
            versionDialog();
        }
        String token = SPUtil.checkToken();
        if (!token.isEmpty()) {
            SNNApplication.connect(token);
        }
        ConversationBehaviorListener();
        UserInfoProvider();
        GroupInfoProvider();
        GroupMemberProvider();
        RiverMsgModel riverMsgModel = new RiverMsgModel(this, null);
        riverMsgModel.getCurrentRiverData();
        RiverChiefModel riverChiefModel = new RiverChiefModel(this, null);
        riverChiefModel.getRiverChiefData(2, false);
        riverChiefModel.getRiverDutyData(1, false);
        alertUtils = new AlertUtils();
        intentService = new Intent(this, WarnService.class);
        mQueue = Volley.newRequestQueue(this);


        userFragment = new UserFragment();
        EventBus.getDefault().register(this);
        //更新
        CheckVersionUtlils.getVersion(this, 0);
        index_rg.setOnCheckedChangeListener(this);
        instanceMineFragment = MineFragment.getInstanceMineFragment();
        newPatrolFragment = NewPatrolFragment.getInstancePatrolFragment();
        instanceStatisticsFragment = StatisticsFragment.getInstanceStatisticsFragment();
        instanceDailyFragment = DailyFragment.getInstanceDailyFragment();
        //为了开启定位
        swithFragment(newPatrolFragment, null);
        swithFragment(nowFragment1, instanceDailyFragment);

        spashTimeUtils = new SpashTimeUtils(this);
        spashTimeUtils.startCutDown();


        intent = new Intent(this, PlayerMusicService.class);
        GPSSetting();
        ProblemTypeModel problemTypeModel = new ProblemTypeModel(this, null);
        problemTypeModel.getProblemTypeData();
        problemTypeModel.getPatrolRiver();


        screenManager = ScreenManager.getInstance(MainActivity.this);
        ScreenBroadcastListener listener = new ScreenBroadcastListener(this);
        listener.registerListener(new ScreenBroadcastListener.ScreenStateListener() {
            @Override
            public void onScreenOn() {
//                screenManager.finishActivity();
            }

            @Override
            public void onScreenOff() {
//                screenManager.startActivity();
            }
        });


    }

    @Override
    protected void onStart() {
        super.onStart();
        if (unReadMessageObserver != null) {
            return;
        }
        unReadMessageObserver = new IUnReadMessageObserver() {
            @Override
            public void onCountChanged(int i) {
                if (badgeView != null) {
                    badgeView.setBadgeCount(i);
                }
            }
        };
        RongIM.getInstance().addUnReadMessageCountChangedObserver(unReadMessageObserver, Conversation.ConversationType.PRIVATE, Conversation.ConversationType.GROUP);

        //默认是有声音
        final boolean isHadVoice = (Boolean) SPUtil.get("isHasVoice", true);
        //设置即时通讯是否播放消息提示音
        RongIM.setOnReceiveMessageListener(new RongIMClient.OnReceiveMessageListener() {
            @Override
            public boolean onReceived(Message message, int i) {
                if (isHadVoice) {
                    return false;
                } else {
                    return true;
                }
            }
        });

        RongIM.setConversationListBehaviorListener(new RongIM.ConversationListBehaviorListener() {

            @Override
            public boolean onConversationPortraitClick(Context context, Conversation.ConversationType conversationType, String s) {
                return false;
            }

            @Override
            public boolean onConversationPortraitLongClick(Context context, Conversation.ConversationType conversationType, String s) {
                return false;
            }

            @Override
            public boolean onConversationLongClick(Context context, View view, final UIConversation uiConversation) {
                final Dialog dialog = new Dialog(MainActivity.this.activity);

                LayoutInflater inflater = MainActivity.this.activity.getLayoutInflater();
                View view1 = inflater.inflate(R.layout.rc_dialog_popup_options, null);
                final ListView listView = (ListView) view1.findViewById(R.id.rc_list_dialog_popup_options);
                //listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_expandable_list_item_1,getData()));
                final SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, getData(uiConversation.isTop()), R.layout.rc_dialog_popup_options_item,
                        new String[]{"name"},
                        new int[]{R.id.rc_dialog_popup_item_name});
                listView.setAdapter(adapter);

                //添加点击事件
                listView.setOnItemClickListener((arg0, view2, position, id) -> {
                    //获得选中项的HashMap对象
                    HashMap<String, String> map = (HashMap<String, String>) listView.getItemAtPosition(position);
                    String name = map.get("name");
                    if (name.equals("置顶聊天")) {
                        RongIM.getInstance().setConversationToTop(uiConversation.getConversationType(), uiConversation.getConversationTargetId(), true, null);
                    } else if (name.equals("取消置顶")) {
                        RongIM.getInstance().setConversationToTop(uiConversation.getConversationType(), uiConversation.getConversationTargetId(), false, null);
                    } else if (name.equals("删除该聊天")) {
                        RongIM.getInstance().clearMessages(uiConversation.getConversationType(), uiConversation.getConversationTargetId(), null);
                        RongIM.getInstance().removeConversation(uiConversation.getConversationType(), uiConversation.getConversationTargetId(), null);
                    }
                    Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();

                    dialog.dismiss();
                });

                // 关闭标题栏，setContentView() 之前调用
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog.setContentView(view1);
                dialog.setCanceledOnTouchOutside(true);

                android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(MainActivity.this.activity);
                builder.create();
                dialog.show();
                return true;
            }

            public List<Map<String, Object>> getData(boolean isTop) {

                List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                Map<String, Object> map = new HashMap<String, Object>();
                if (isTop)
                    map.put("name", "取消置顶");
                else
                    map.put("name", "置顶聊天");
                list.add(map);

                map = new HashMap<String, Object>();
                map.put("name", "删除该聊天");
                list.add(map);

                return list;
            }

            @Override
            public boolean onConversationClick(Context context, View view, UIConversation uiConversation) {
                return false;
            }
        });
    }

    private void GroupMemberProvider() {
        RongCallKit.setGroupMemberProvider((groupId, result) -> {
            String url = NetUrl.baseUrl + "rong/web/getUserByGroupId?groupId=" + groupId + "&page=1&pageSize=100000";
            StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        int status = jsonObject.getInt("status");
                        if (status == 200) {
                            JSONArray data = jsonObject.getJSONArray("result");
                            ArrayList<String> list = new ArrayList<>();
                            for (int i = 0; i < data.length(); i++) {
                                JSONObject info = data.getJSONObject(i);
                                list.add(info.getString("id"));
                            }

                            result.onGotMemberList(list);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });
            mQueue.add(stringRequest);
            return null;
        });


    }


    /**
     * 群用户提供者
     */
    private void GroupInfoProvider() {
        RongIM.setGroupInfoProvider(id -> {
            getGroupInfos(id, new GetMyGroupInfoListener() {
                @Override
                public Group onSuccess(Group groupInfo) {
                    RongIM.getInstance().refreshGroupInfoCache(groupInfo);
                    return null;
                }
            });

            return null;
        }, true);

    }


    private void getGroupInfos(final String id, final GetMyGroupInfoListener listener) {
        String url = NetUrl.baseUrl + "rong/web/getGroupById?id=" + id;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, s -> {

            try {
                JSONObject jsonObject = new JSONObject(s);
                int status = jsonObject.getInt("status");
                if (status == 200) {
                    JSONObject info = jsonObject.getJSONObject("result");
                    Group group = new Group(id, info.getString("NAME"), Uri.parse("hha"));

                    listener.onSuccess(group);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }, volleyError -> {

        });
        mQueue.add(stringRequest);
    }


    public interface GetMyGroupInfoListener {
        public Group onSuccess(Group groupInfo);
    }


    /**
     * 会话消息点击监听
     */
    private void ConversationBehaviorListener() {
        RongIM.setConversationBehaviorListener(new RongIM.ConversationBehaviorListener() {

            //点击头像
            @Override
            public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
                if (conversationType.getName().equals("private")) {
                    showuserinfo(userInfo.getUserId(), context);
                } else {
                    RongIM.getInstance().startPrivateChat(MainActivity.this, userInfo.getUserId(), userInfo.getName());
                }


                return true;
            }

            //长按头像
            @Override
            public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
                return false;
            }

            //点击消息
            @Override
            public boolean onMessageClick(Context context, View view, Message message) {
                switch (message.getObjectName()) {
                    case "RC:ImgMsg":
                        //图片
                        break;
                    case "RC:TxtMsg":
                        break;
                    case "RC:LBSMsg":
                        //位置

                        break;
                }
                return false;
            }

            //点击消息里的链接
            @Override
            public boolean onMessageLinkClick(Context context, String s) {
                return false;
            }

            //长按消息
            @Override
            public boolean onMessageLongClick(Context context, View view, Message message) {
                return false;
            }
        });

    }

    private void showuserinfo(final String userid, final Context context) {
        String url = NetUrl.baseUrl + "sysUserB/getAppUserByUserId?userId=" + userid;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONObject info = jsonObject.getJSONObject("user");
                    String name = info.getString("name");
                    String mobile = info.getString("mobile");
                    String job = info.getString("job");
                    String rivertype = info.getString("rivertype");
                    String address = info.getString("city") + info.getString("area") + info.getString("town") + info.getString("village");
                    android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context);

                    builder.setMessage("姓名：" + name + "\n电话：" + mobile + "\n区域：" + address + "\n用户类别：" + rivertype + "\n职务:" + job);
                    builder.setPositiveButton("关闭", null);
                    builder.create().show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        }, error -> {

        });
        mQueue.add(stringRequest);
    }

    private void UserInfoProvider() {

        //内容提供者
        RongIM.setUserInfoProvider(userid -> {


            getuinfo(userid, new GetUserInfoListener() {
                @Override
                public UserInfo onSuccess(UserInfo userInfo) {
                    //  Log.i("内容提供者","用户名称"+userInfo.getName());
                    RongIM.getInstance().refreshUserInfoCache(userInfo);
                    SPUtil.put(userInfo.getUserId(), userInfo.getName());
                    return null;
                }

                @Override
                public void onError(String userId, Exception e) {

                }
            });
            return null;
        }, true);
    }

    /**
     * 通过网络获取用户信息
     *
     * @return
     */
    private UserInfo getuinfo(final String uid, final GetUserInfoListener listener) {

        String url = NetUrl.baseUrl + "sysUserB/getAppUserByUserId?userId=" + uid;


        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                response -> {

                    try {
                        JSONObject json = new JSONObject(response);
                        int status = json.getInt("status");

                        if (status == 200) {
                            JSONObject data = json.getJSONObject("user");
                            String avatar = "";
                            String nickname = data.getString("name");
                            Log.i("TAG", "昵称" + nickname);
                            UserInfo userInfo = new UserInfo(uid, nickname, Uri.parse(avatar));
                            listener.onSuccess(userInfo);
                        }

                    } catch (JSONException e) {
                        Log.i("网络请求", "解析JSON异常");
                    }

                }, error -> {

        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("uid", uid);
                return map;
            }
        };
        mQueue.add(stringRequest);
        return null;
    }


    public interface GetUserInfoListener {
        UserInfo onSuccess(UserInfo userInfo);

        void onError(String userId, Exception e);
    }

    private void GPSSetting() {
        //如果没有打开GPS定位，那么打开GPS定位
        LocationManager locationManager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);
        // 判断GPS模块是否开启，如果没有则开启
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            ToastUtils.SingleToastUtil(this, "请打开GPS");
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setMessage("请打开GPS");
            dialog.setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            // 转到手机设置界面，用户设置GPS
                            Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, 0); // 设置完成后返回到原来的界面
                        }
                    });
            dialog.setNeutralButton("取消", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    arg0.dismiss();
                }
            });
            dialog.show();
        } else {

        }
    }

    private void login(final String username, final String password, Boolean isSign, String devicecode) {
        HttpManager.getInstance()
                .login(username, password, isSign, devicecode, null)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ApiSubscriber(this, new ApiSubscriber.HttpOnResultListener<LoginBean>() {
                    @Override
                    public void onNext(LoginBean jsonObject) {
                        if (jsonObject.getCode() == 1) {
                            SPUtil.put("token", jsonObject.getToken());
                            SPUtil.put("userId", jsonObject.getData().getId());
                            SPUtil.put("name", jsonObject.getData().getName());
                            SPUtil.put("login_name", jsonObject.getData().getLoginName());
                            SPUtil.put("roleNames", jsonObject.getData().getRoleNames());
                            SPUtil.put("addvcd", jsonObject.getData().getAddvcd());
                            SPUtil.put("password", password);
                            SPUtil.put("phone", jsonObject.getData().getMobile());
                            SPUtil.put("newVersion", "5.3");
                            SPUtil.put("userType", jsonObject.getData().getUserType());
                            SPUtil.put("UserInfo", jsonObject.getData());

                            EventBus.getDefault().post(new ClickEvent("loging_success"));
                        } else {
                            doActivity(LoginActivity.class);
                            finish();
                        }
                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onstart() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                }));
    }

    private void versionDialog() {
        new AlertDialog.Builder(this)
                .setTitle("系统提示")
                .setMessage("您的手机Android版本号低于5.0,程序继续运行将可能出现闪退等现象，请更换手机或升级系统至5.0以上")
                .setPositiveButton("我知道了", (dialogInterface, i) -> {
                    //提交记录
                })
                .show();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void helloEventBus(ClickEvent message) {
        if (message.getMsg().equals("zonghezixun")) {
        } else if (message.getMsg().equals("xunhe")) {
            rb_patrol.setChecked(true);
        }
    }

    public void initJspush() {
        Set<String> set = new HashSet<String>();
        set.add(SPUtil.get("roleId", "1111").toString());
        JPushInterface.setAliasAndTags(getApplicationContext(), SPUtil.get("userId", "").toString(), set, new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set<String> set) {

            }
        });
    }

    /**
     * @param nowFragment  当前的fragment
     * @param nextFragment 即将切换的fragment
     */
    public void swithFragment(Fragment nowFragment, Fragment nextFragment) {
        nowFragment1 = nextFragment;
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
        if (nextFragment == null) {
            fragmentTransaction.add(R.id.fragments, nowFragment).commit();
            nowFragment1 = nowFragment;
        } else {
            if (nextFragment.isAdded()) {
                fragmentTransaction.hide(nowFragment).show(nextFragment).commit();
            } else {
                fragmentTransaction.hide(nowFragment).add(R.id.fragments, nextFragment).commit();

            }
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i) {
            case R.id.rb_daily:
                swithFragment(nowFragment1, instanceDailyFragment);
                break;
            case R.id.rb_statics:
                swithFragment(nowFragment1, instanceStatisticsFragment);
                break;
            case R.id.rb_mine:
                swithFragment(nowFragment1, instanceMineFragment);
                break;
            case R.id.rb_patrol:
                swithFragment(nowFragment1, newPatrolFragment);
                break;
            case R.id.rb_user:
                swithFragment(nowFragment1, userFragment);
                break;

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        JPushInterface.onKillProcess(this);
        AppManager.getInstance().removeActivity(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
        if (isSwitchUserFrahment) {
            isSwitchUserFrahment = false;
            rb_user.setChecked(true);
        }
    }


    @Override
    public void onSuccess() {
        rl_spash.setVisibility(View.GONE);

    }

    @Override
    public void onFinshed() {
        rl_spash.setVisibility(View.GONE);

    }

    @Override
    public void onProgress(int progress) {
        tv_time.setText(progress + "s");
    }

    public void updateNumMsg() {
        if (instanceMineFragment != null) {
            instanceDailyFragment.getProblemNum(SPUtil.get("userId", "null").toString());
        }

    }

    private long firstTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        long secondTime = System.currentTimeMillis();
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (secondTime - firstTime < 2000) {
                if (newPatrolFragment != null && newPatrolFragment.isPatrolling()) {
                    alertUtils.setTitle("提示");
                    alertUtils.setMsg("您当前巡河未结束，为了保证系统能正常记录你的巡河轨迹，请结束巡河后再进行退出");
                    alertUtils.displayDiago(MainActivity.this, new AlertUtils.IClickButton() {
                        @Override
                        public void ensure() {
                            newPatrolFragment.stopCurrentPatrol();
                            alertUtils.closeDialog();
                        }

                        @Override
                        public void cancel() {
                            System.exit(0);
                        }
                    });
                } else {
                    System.exit(0);
                }
            } else {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = System.currentTimeMillis();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    public void switchFrament(boolean isSwitchUserFrahment) {
        this.isSwitchUserFrahment = isSwitchUserFrahment;
    }

    public void startService() {
        if (newPatrolFragment.isPatrolling()) {
            startService(intentService);
            startPlayMusicService();
        }
    }


    public void stopServoce() {
        if (newPatrolFragment.isPatrolling()) {
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            manager.cancel(WarnService.NOTIFICATION_ID);
            stopService(intentService);
            stopPlayMusicService();
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (isFocus) {
            return;
        }
        isFocus = true;
        int measuredHeight = rb_patrol.getMeasuredHeight();
        ViewGroup.LayoutParams layoutParams = rb_bag.getLayoutParams();
        layoutParams.height = measuredHeight + 5;
        layoutParams.width = rb_patrol.getMeasuredWidth();
        rb_bag.requestLayout();
        badgeView = new BadgeView(MainActivity.this);
        badgeView.setTargetView(rb_bag);
//        badgeView.setBadgeCount(0);
    }

    private void stopPlayMusicService() {
        stopService(intent);
    }

    private void startPlayMusicService() {
        startService(intent);
    }
}
